package blog.controller.blog;


import blog.controller.vo.CommentDetailVo;
import blog.controller.vo.CommentPageResult;
import blog.entity.*;
import blog.service.*;
import blog.util.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 博客页面控制器
 */

@Controller
public class BlogPageController {

    @Autowired
    private BlogService blogService;

    @Autowired
    private TagService tagService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private BlogTagService blogTagService;

    /**
     * 主页
     *
     * @return
     */
    @RequestMapping({"/", "/index", "index.html"})
    public String toIndex(HttpServletRequest request) {
        return this.page(request, 1);
    }

    /**
     * 关于页
     *
     * @return
     */
    @RequestMapping({"/about"})
    public String toAbout() {
        return "blog/yummy-jekyll/about";
    }

    /**
     * 首页 分页数据
     *
     * @return
     */
    @GetMapping({"/page/{pageNum}"})
    public String page(HttpServletRequest request, @PathVariable("pageNum") Integer pageNum) {
        //每页显示 5 条博客
        System.out.println("test");
        Page<Blog> page = new Page<>(pageNum, 5);
        blogService.page(page, null);
        if (page.getRecords() == null) {
            return "error/error_404";
        }
        System.out.println(page.getRecords() == null);
        System.out.println(tagService.list());
        request.setAttribute("page", page);
        request.setAttribute("tags", tagService.list());
        return "blog/yummy-jekyll/index";
    }

    /**
     * 详情页
     *
     * @return
     */
    @GetMapping({"/blog/{blogId}", "/article/{blogId}"})
    public String detail(HttpServletRequest request,
                         @PathVariable("blogId") int blogId,
                         @RequestParam(value = "commentPage", required = false, defaultValue = "1") Integer commentPage) {
        Blog blog = blogService.getById(blogId);
        if (blog != null) {
            request.setAttribute("blog", blog);
            //此处应该是评论的分页对象（默认每页显示三条评论）
            request.setAttribute("commentPageResult", commentService.createCommentPageResult(blogId, commentPage, 3));
        }
        //用于配置页面标题，页头，页脚等信息，这里的话，我决定写死
        request.setAttribute("pageName", "详情");
        //request.setAttribute("configurations", configService.getAllConfigs());
        return "blog/yummy-jekyll/detail";
    }

    /**
     * 标签列表页
     *
     * @return
     */
    @GetMapping({"/tag/{tagName}"})
    public String tag(HttpServletRequest request, @PathVariable("tagName") String tagName) {
        return tag(request, tagName, 1);
    }

    /**
     * 标签列表页
     *
     * @return
     */
    @GetMapping({"/tag/{tagName}/{pageNum}"})
    public String tag(HttpServletRequest request, @PathVariable("tagName") String tagName, @PathVariable("page") Integer pageNum) {
        Tag tag = tagService.getOne(new QueryWrapper<Tag>().eq("tag_name", tagName));
        List<BlogTag> blogTagList = blogTagService.list(new QueryWrapper<BlogTag>().eq("tag_id", tag.getId()));
        List<Integer> blogIds = new ArrayList<>();
        for (BlogTag blogTag : blogTagList) {
            blogIds.add(blogTag.getBlogId());
        }
        //每页 5 条
        Page<Blog> page = new Page<>(pageNum, 5);
        blogService.page(page, new QueryWrapper<Blog>().in("id", blogIds));
        request.setAttribute("page", page);
        request.setAttribute("pageName", "标签");
        request.setAttribute("pageUrl", "tag");
        request.setAttribute("keyword", tagName);
//        request.setAttribute("newBlogs", blogService.getBlogListForIndexPage(1));
//        request.setAttribute("hotBlogs", blogService.getBlogListForIndexPage(0));
//        request.setAttribute("hotTags", tagService.getBlogTagCountForIndex());
//        request.setAttribute("configurations", configService.getAllConfigs());
        return "blog/yummy-jekyll/list";
    }

    /**
     * 搜索列表页
     *
     * @return
     */
    @GetMapping({"/search/{keyword}"})
    public String search(HttpServletRequest request, @PathVariable("keyword") String keyword) {
        return search(request, keyword, 1);
    }

    /**
     * 搜索列表页
     *
     * @return
     */
    @GetMapping({"/search/{keyword}/{pageNum}"})
    public String search(HttpServletRequest request, @PathVariable("keyword") String keyword, @PathVariable("page") Integer pageNum) {
        // 5 条 1 页
        Page<Blog> page = new Page<>(pageNum, 5);
        //查询博客的 内容 或 标题 含有 关键字 的博客
        blogService.page(page, new QueryWrapper<Blog>().like("content", keyword).or().like("title", keyword));
        request.setAttribute("page", page);
        request.setAttribute("pageUrl", "search");
        request.setAttribute("keyword", keyword);
        request.setAttribute("pageName", "搜索结果");
//        request.setAttribute("newBlogs", blogService.getBlogListForIndexPage(1));
//        request.setAttribute("hotBlogs", blogService.getBlogListForIndexPage(0));
//        request.setAttribute("hotTags", tagService.getBlogTagCountForIndex());
//        request.setAttribute("configurations", configService.getAllConfigs());
        return "blog/yummy-jekyll/list";
    }

    /**
     * 评论操作
     */
    @PostMapping("/blog/comment")
    @ResponseBody
    public Result comment(HttpServletRequest request,
                          HttpSession session,
                          @RequestParam Integer blogId,             //博客id
                          @RequestParam String verifyCode,      //用户输入验证码
                          @RequestParam String nickName,     //评论者昵称
                          @RequestParam String email,           //评论者邮箱
                          @RequestParam String commentBody) {   //评论内容
        //输入校验
        if (StringUtils.isEmpty(verifyCode)) {
            return ResultGenerator.genFailResult("验证码不能为空");
        }
        String kaptchaCode = session.getAttribute("verifyCode") + "";
        if (StringUtils.isEmpty(kaptchaCode)) {
            return ResultGenerator.genFailResult("非法请求");
        }
        if (!verifyCode.equals(kaptchaCode)) {
            return ResultGenerator.genFailResult("验证码错误");
        }
        String ref = request.getHeader("Referer");
        if (StringUtils.isEmpty(ref)) {
            return ResultGenerator.genFailResult("非法请求");
        }
        if (null == blogId || blogId < 0) {
            return ResultGenerator.genFailResult("非法请求");
        }
        if (StringUtils.isEmpty(nickName)) {
            return ResultGenerator.genFailResult("请输入称呼(昵称)");
        }
        if (StringUtils.isEmpty(email)) {
            return ResultGenerator.genFailResult("请输入邮箱地址");
        }
        if (!PatternUtil.isEmail(email)) {
            return ResultGenerator.genFailResult("请输入正确的邮箱地址");
        }
        if (StringUtils.isEmpty(commentBody)) {
            return ResultGenerator.genFailResult("请输入评论内容");
        }
        if (commentBody.trim().length() > 200) {
            return ResultGenerator.genFailResult("评论内容过长");
        }
        Comment comment = new Comment();
        comment.setBlogId(blogId);
        //将 userInfo 的 id 关联上
        UserInfo checkUserInfo = userInfoService.getOne(new QueryWrapper<UserInfo>().eq("email", email));
        if(checkUserInfo == null){
            UserInfo userInfo = new UserInfo();
            userInfo.setNickName(BlogUtils.cleanString(nickName));
            userInfo.setEmail(email);
            userInfoService.save(userInfo);
            comment.setInfoId(userInfo.getId());
        }
        else if (checkUserInfo != null && !checkUserInfo.getNickName().equals(nickName)){
            return ResultGenerator.genFailResult("该邮箱已注册");
        }
        else{
            comment.setInfoId(checkUserInfo.getId());
        }
        comment.setContent(BlogUtils.cleanString(commentBody));
        comment.setCreateTime(TimeUtils.getTime());
        comment.setUpdateTime(TimeUtils.getTime());
        return ResultGenerator.genSuccessResult(commentService.save(comment));
    }

}
